<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @closed="dialogClose"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="140px"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="dataForm.name" />
      </el-form-item>
      <el-form-item label="角色编码" prop="code">
        <el-input v-model="dataForm.code" />
      </el-form-item>
      <el-form-item label="角色描述" prop="descript">
        <el-input v-model="dataForm.descript" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import RoleApi from "@/api/system/role";
export default {
  data() {
    return {
      visible: false,
      dataForm: {},
      dataRule: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    init(id) {
      this.visible = true;
      if (id) {
        this.dataForm.id = id;
        this.$nextTick(() => {
          RoleApi.getRole({ id }).then(({ data }) => {
            this.dataForm = data;
          });
        });
      }
    },
    dialogClose() {
      this.dataForm = {};
      this.$refs["dataForm"].resetFields();
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          if (this.dataForm.id) {
            RoleApi.updateRole(this.dataForm).then(({ data }) => {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            });
          } else {
            RoleApi.createRole(this.dataForm).then(({ data }) => {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            });
          }
        }
      });
    },
  },
};
</script>
